package com.hyyt.shopjsp.statistics.controller;

import com.hyyt.shopjsp.basic.vo.BasicCustomerVo;
import com.hyyt.shopjsp.basic.service.IBasicCustomerService;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.util.common.EnumUtils;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.export.ExportExcel;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘超 on 2017/7/19.
 */

@Controller
@RequestMapping("/back/customerStatistics")
public class CustomerStatisticsController extends BaseController{

    private Logger logger = Logger.getLogger(CustomerStatisticsController.class);
    private String basePath = "/back/shop/statistics/";

    @Resource
    private IBasicCustomerService basicCustomerService;

    /**
     * 跳转会员统计页面
     *
     * @return 返回到指定页面
     */
    @RequestMapping("gotoCustomerStatistics")
    public String gotoCustomerStatistics(){
        return basePath + "customerStatisticsList";
    }

    /**
     * 会员统计列表
     * @param page
     * @param loginName  用户名
     * @param createTimeStart  开始时间
     * @param createTimeEnd    结束时间
     */
    @RequestMapping(value="listCustomerStatistics",method= RequestMethod.POST)
    @ResponseBody
    public void listCustomerStatistics(Page page,String createTimeStart,String createTimeEnd,String loginName,HttpServletResponse response){
        Map<String, Object> params=new HashMap<>();
        if(Utils.objectIsNotEmpty(loginName)){
            params.put("loginName", loginName.trim());
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart", createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd", createTimeEnd);
        }
        int totalRecordCount =basicCustomerService.countCustomerStatistics(params);
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<BasicCustomerVo> basicCustomerList=basicCustomerService.queryCustomerStatistics(params, page.getPageRecordBeginIndex(), page.getPageSize());
        params.clear();
        params.put("total", totalRecordCount);// total键 存放总记录数，必须的
        params.put("rows", basicCustomerList);// rows键 存放每页记录 list
        ResultMsg.create(params, response);  //把内容发送到页面
    }

    /**
     * 导出会员统计excel
     * @param createTimeStart
     * @param createTimeEnd
     * @param loginName
     * @param request
     * @param response
     */
    @RequestMapping("exportCustomerStatisticsExcel")
    public void exportCustomerStatisticsExcel(String createTimeStart, String createTimeEnd, String loginName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        Map<String, Object> params=new HashMap<>();
        if(Utils.objectIsNotEmpty(loginName)){
            /**get请求强转中文，防止乱码**/
            loginName=new String(loginName.trim().getBytes("ISO-8859-1"),"UTF-8");
            params.put("loginName", loginName.trim());
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart", createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd", createTimeEnd);
        }
        List<BasicCustomerVo> basicCustomerList=basicCustomerService.queryCustomerStatistics(params);
        SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
        List<Map<String,Object>> customerStatistics = new ArrayList<>();
        if(basicCustomerList!=null&&basicCustomerList.size()>0){
            for (BasicCustomerVo basicCustomerVo : basicCustomerList) {
                Map<String,Object> map = new HashMap<>();
                map.put("loginName", basicCustomerVo.getLoginName());
                map.put("salesCount", basicCustomerVo.getSalesCount());
                map.put("salesPrice", basicCustomerVo.getSalesPrice());
                if(Utils.objectIsNotEmpty(basicCustomerVo.getRefundCount())){
                    map.put("refundCount", basicCustomerVo.getRefundCount());
                }else{
                    map.put("refundCount","0");
                }
                map.put("refundPrice", basicCustomerVo.getRefundPrice());
                customerStatistics.add(map);
            }
        }
        String fileName ="会员统计";
        String columnNames[] = {"会员名称","已付款订单数量（单）","已付款订单金额（元）","已退货订单数量（单）","已退货订单金额（元）"};
        String keys[] = {"loginName","salesCount","salesPrice","refundCount","refundPrice"};
        try {
            ExportExcel.download(fileName,customerStatistics,columnNames,keys,request,response);
        } catch (IOException e) {
            logger.error("导出Excel失败！");
        }


    }
}
